package ninja.awesome.game;

import ninja.awesome.framework.Game;
import ninja.awesome.framework.Graphics;
import ninja.awesome.framework.Screen;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;

public class HighScoresScreen extends Screen {

	private static final int MARGIN_TOP = NinjaGame.HEIGHT / 2;
	private JSONArray scoresArr;
	private int yourScore = -1;

	public HighScoresScreen(Game game) {
		super(game);
		SharedPreferences preferences = ((NinjaGame) game).getSharedPreferences(NinjaGame.PREF_HIGH_SCORE,
				Context.MODE_APPEND);
		String scores = preferences.getString(NinjaGame.PREF_HIGH_SCORE_ARRAY, "[]");
		try {
			scoresArr = new JSONArray(scores);
		} catch (JSONException e) {
			scoresArr = new JSONArray();
		}
	}

	@Override
	public void update(float deltaTime) {

	}

	@Override
	public void paint(float deltaTime) {
		// TODO Auto-generated method stub
		Graphics g = game.getGraphics();
		g.clearScreen(Color.BLACK);
		Paint p = new Paint();
		p.setTextSize(80);
		p.setColor(Color.YELLOW);
		p.setTextAlign(Align.CENTER);
		p.setTypeface(Assets.fontFace);
		if (yourScore >= 0) {
			g.drawString("Your score: " + yourScore, NinjaGame.WIDTH / 2, 200, p);
		}
		if (scoresArr.length() > 0) {
			try {
				p.setTextSize(60);
				p.setColor(Color.CYAN);
				g.drawString("High Scores", NinjaGame.WIDTH / 2, MARGIN_TOP - 60, p);
				p.setColor(Color.WHITE);
				p.setTextSize(45);
				for (int i = 0; i < scoresArr.length(); ++i) {
					JSONObject scoreObj = scoresArr.getJSONObject(i);
					g.drawString(scoreObj.getString("id") + "    " + scoreObj.getInt("scores"), NinjaGame.WIDTH / 2,
							MARGIN_TOP + i * 55, p);
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
			g.drawString("No record found.", NinjaGame.WIDTH / 2, NinjaGame.HEIGHT / 2, p);
		}
	}

	@Override
	public void dispose() {
	}

	@Override
	public void backButton() {
		game.setScreen(new MainMenuScreen(game));
	}

	public int getYourScore() {
		return yourScore;
	}

	public void setYourScore(int yourScore) {
		this.yourScore = yourScore;
	}

	@Override
	public void pause() {

	}

	@Override
	public void resume() {

	}

}
